/**
 * Created by Sahaka on 12/01/16.
 */

var Config = {
    createUrl: '/api/companyProduct',
};

var ConfigDiscount = {
    selectUrl: '/api/localDiscount'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
$().ready(function () {
    $.ajax(
        {
            url: ConfigDiscount.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var goodsType = [];
                goodsType.push('<option value="0" hassubinfo="true">折扣类型</option>');
                data.data.map(function (category) {
                    goodsType.push('<option value="');
                    goodsType.push(category.discountId);
                    goodsType.push('" ');
                    goodsType.push('hassubinfo="true">');
                    if(category.discount == 100){
                        goodsType.push("不打折, 不送红包");
                    }else{
                        goodsType.push((category.discount) + "折,单笔消费 ¥" + category.limitPrice/100 + "元，送" + category.score + "红包");
                    }
                    goodsType.push('</option>');
                });
                $("#discountId").html(goodsType.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });

    $('#submitCreate').click(function () {

        $("#ajaxform").validate();

        if ($('#ajaxform').valid()) {
            var postData = $('#ajaxform').serializeArray();
            $.ajax(
                {
                    url: Config.createUrl,
                    type: "POST",
                    data: postData,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        toastr.success(data.msg, data.title);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        }
        return false;
    });
});
